package com.ruoyi.web.controller.boc;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.boc.domain.BocLakeImport;
import com.ruoyi.boc.service.IBocLakeTableColumnService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.generator.util.VelocityInitializer;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.boc.domain.BocLakeTable;
import com.ruoyi.boc.service.IBocLakeTableService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入湖生成业务Controller
 * 
 * @author ruoyi
 * @date 2025-02-14
 */
@RestController
@RequestMapping("/boc/lakeTable")
public class BocLakeTableController extends BaseController
{
    @Autowired
    private IBocLakeTableService bocLakeTableService;
    @Autowired
    private IBocLakeTableColumnService bocLakeTableColumnService;

    /**
     * 查询入湖生成业务列表
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:list')")
    @GetMapping("/list")
    public TableDataInfo list(BocLakeTable bocLakeTable)
    {
        startPage();
        List<BocLakeTable> list = bocLakeTableService.selectBocLakeTableList(bocLakeTable);
        return getDataTable(list);
    }

    /**
     * 导出入湖生成业务列表
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:export')")
    @Log(title = "入湖生成业务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BocLakeTable bocLakeTable)
    {
        List<BocLakeTable> list = bocLakeTableService.selectBocLakeTableList(bocLakeTable);
        ExcelUtil<BocLakeTable> util = new ExcelUtil<BocLakeTable>(BocLakeTable.class);
        util.exportExcel(response, list, "入湖生成业务数据");
    }

    /**
     * 获取入湖生成业务详细信息
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:query')")
    @GetMapping(value = "/{tableId}")
    public AjaxResult getInfo(@PathVariable("tableId") Long tableId)
    {
        return success(bocLakeTableService.selectBocLakeTableByTableId(tableId));
    }

    /**
     * 新增入湖生成业务
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:add')")
    @Log(title = "入湖生成业务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BocLakeTable bocLakeTable)
    {
        return toAjax(bocLakeTableService.insertBocLakeTable(bocLakeTable));
    }

    /**
     * 修改入湖生成业务
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:edit')")
    @Log(title = "入湖生成业务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BocLakeTable bocLakeTable)
    {
        return toAjax(bocLakeTableService.updateBocLakeTable(bocLakeTable));
    }

    /**
     * 删除入湖生成业务
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:remove')")
    @Log(title = "入湖生成业务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tableIds}")
    public AjaxResult remove(@PathVariable Long[] tableIds)
    {
        bocLakeTableColumnService.deleteBocLakeTableColumnByTableIds(tableIds);
        return toAjax(bocLakeTableService.deleteBocLakeTableByTableIds(tableIds));
    }

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:list')")
    @GetMapping("/db/list")
    public TableDataInfo dataList(BocLakeTable bocLakeTable)
    {
        List<BocLakeTable> list1 = bocLakeTableService.selectGbaseTableList(bocLakeTable);
        List<BocLakeTable> list2 = bocLakeTableService.selectBocLakeTableList(bocLakeTable);
        List<BocLakeTable> list3 = new ArrayList<BocLakeTable>();
        for(int i=0;i<list1.size();i++){
            String tableNamelist1 = list1.get(i).getTableName();
            int flat = 0;
            for(int j =0;j<list2.size();j++){
                String tableNamelist2 = list2.get(j).getTableName();
                if(tableNamelist1.equals(tableNamelist2)){
                    flat = 1;
                    break;
                }
            }
            if(flat == 0){
                list3.add( list1.get(i));
            }
        }
        return getDataTable(list3);
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:import')")
    @Log(title = "导入湖表", businessType = BusinessType.IMPORT)
    @PostMapping("/importGbaseTable")
    public AjaxResult importTableSave(String tables)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<BocLakeTable> tableList = bocLakeTableService.selectGbaseTableListByNames(tableNames);
        bocLakeTableService.importGbaseTable(tableList);
        return success();
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:export')")
    @Log(title = "生成湖代码", businessType = BusinessType.GENCODE)
    @GetMapping("/downLoadLakeCode")
    public void downLoadLakeCode(HttpServletResponse response, long tableId) throws IOException {

       bocLakeTableService.downloadLakeCode(response,tableId);
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@ss.hasPermi('boc:lakeTable:export')")
    @Log(title = "生成湖代码", businessType = BusinessType.GENCODE)
    @GetMapping("/batchDownLoadLakeCode")
    public void batchDownLoadLakeCode(HttpServletResponse response, String tableIds) throws IOException {

        Long[] ids = Convert.toLongArray(tableIds);
        byte[] data = bocLakeTableService.downloadLakeCode(ids);
        genLakeCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genLakeCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"lake.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 同步数据库
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/synchGbaseDb/{tableName}")
    public AjaxResult synchGbaseDb(@PathVariable("tableName") String tableName)
    {
        bocLakeTableService.synchGbaseDb(tableName);
        return success();
    }

    /**
     * 预览代码
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @GetMapping("/previewLake/{tableId}")
    public AjaxResult previewLake(@PathVariable("tableId") Long tableId) throws IOException
    {
        String code = bocLakeTableService.previewLakeCode(tableId);
        return success(code);
    }

    @Log(title = "入湖管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importBocLakeData")
    public AjaxResult importBocLakeData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BocLakeImport> util = new ExcelUtil<BocLakeImport>(BocLakeImport.class);
        List<BocLakeImport> bocLakeImportList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = bocLakeTableService.importBocLakeData(bocLakeImportList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importBocLakeTemplate")
    public void importBocLakeTemplate(HttpServletResponse response)
    {
        ExcelUtil<BocLakeImport> util = new ExcelUtil<BocLakeImport>(BocLakeImport.class);
        util.importTemplateExcel(response, "入湖数据");
    }

}
